/**
 * 
 */
package ssdi.carrentalsystem.utils;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author haarthi
 * 
 *         DBConnector is a utility class for connecting with the database
 */
public class DBConnectorFactory {
	// JDBC driver name and database URL
	private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	private static final String DB_URL = "jdbc:mysql://localhost/ssdi";

	// Database credentials
	private static final String USER = "root";
	private static final String PASS = "root";
	private static DBConnectorFactory connectionInstance;

	private DBConnectorFactory() {
		try {
			Class.forName(JDBC_DRIVER);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * create a connection with the database
	 */
	public Connection getDBConnection() throws Exception {
		Connection conn;
		System.out.println("Connecting to the database");
		try {
			conn = DriverManager.getConnection(DB_URL, USER, PASS);
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(UserMessages.ERROR_CONNECTING_DB);
		}
	}

	/*
	 * Close the DB connection
	 */
	public void closeDBConnection(Connection conn) throws Exception {
		try {
			if (conn != null)
				conn.close();
		} catch (Exception se) {
			se.printStackTrace();
			throw new Exception(UserMessages.ERROR_CONNECTING_DB);
		}
	}

	public static DBConnectorFactory getInstance() {
		if (connectionInstance == null) {
			connectionInstance = new DBConnectorFactory();
		}
		return connectionInstance;
	}
}